/**
 * 框架上下文
 * 封装了公用的API
 */
layui.define(['layer', 'form', 'zlmessenger', 'messenger', 'zlConfig', 'util'], function (exports) {
    "use strict";
    var $ = layui.$,
        form = layui.form,
        util = layui.util,
        userVo = undefined,
        messenger = layui.zlmessenger('Parent', 'zlfw'),
        zlContext = {
            /**错误msg提示 */
            errorMsg: function (text) {
                var top = zlContext.kdayunIframe();
                top.layer.msg(text, {
                    icon: 2,
                    time: 5000
                });
            },
            /**成功 msg提示 */
            successMsg: function (text) {
                var top = zlContext.kdayunIframe();
                top.layer.msg(text, {
                    icon: 1,
                    time: 5000
                });

            },
            /**成功 alert提示 */
            successAlert: function (text, callBackFunc) {
                var top = zlContext.kdayunIframe();
                top.layer.alert(text, {
                    icon: 1
                }, function (index) {
                    top.layer.close(index);
                    callBackFunc && callBackFunc();
                });
            },
            /**警告弹出提示*/
            warnMsg: function (text) {
                var top = zlContext.kdayunIframe();
                top.layer.msg(text, {
                    icon: 0
                });
            },
            /**弹出确定取消的对话框 */
            confirm: function (title, text, callBackFunc) {
                layer.confirm(text, {
                    title: title,
                    resize: false,
                    btn: ['确定', '取消'],
                    btnAlign: '',
                    anim: 1,
                    icon: 3
                }, callBackFunc, function () {});
            },
            // 表格,树结构等无数据渲染时 显示无数据提示
            noData: function (dom, isremove) {
                var imgtop = 0,
                    imgsize = 0,
                    fontszie = 0,
                    fonttop = 0;
                if (dom.height() > 150) {
                    imgtop = '40px';
                    imgsize = '80px';
                    fontszie = '22px';
                    fonttop = '10px';
                } else {
                    imgtop = '10px';
                    imgsize = '40px';
                    fontszie = '14px';
                    fonttop = '5px';
                }
                if (isremove) {
                    if (dom.find('.layui-none').length > 0) {
                        dom.find('.layui-none').remove();
                    }
                } else {
                    if (dom.find('.layui-none').length == 0) {
                        dom.append(
                            '<div class="layui-none" style="padding-bottom: 0;">  ' +
                            '  <div class="empty-data" style="text-align:center;padding-top: ' + imgtop + ';font-size: 25px;color: #ccc;font-family: tahoma ,微软雅黑;">' +
                            '    <i class="layui-icon layui-icon-search" style="font-size: ' + imgsize + ';"></i>   ' +
                            '    <div style="padding-top: ' + fonttop + ';font-size: ' + fontszie + ';">无数据</div>' +
                            '  </div>' +
                            '</div>'
                        );
                    }
                }
            },
            /**
             * 显示loading加载框
             */
            showLoading: function (msg) {
                return layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
            },
            /**
             * 关闭loading框
             */
            closeLoading: function (index) {
                layer.close(index);
            },
            /**获取当前激活的iframe */
            getactiveiframe: function () {
                var parents = window.parent,
                    i = 0;
                // 避免死循环
                while ($(parents.document).find('.layadmin-tabsbody-item.layui-show').length == 0 && i < 4) {
                    parents = parents.parent;
                    i++;
                }
                return $(parents.document).find('.layadmin-tabsbody-item.layui-show').find('iframe');
            },
            /**ajax请求 */
            zlajax: function (url, method, param, contextType, callBackFunc, async, showLoading) {
                //打开加载层               
                var $iframe = zlContext.getactiveiframe();
                if ($iframe.length > 0 && param != null) {
                    try {
                        if (typeof param == 'string') {
                            param = eval('(' + param + ')');
                        }

                        // 数组
                        if (param instanceof Array) {
                            if (param[0]['FUNCTIONID_ZLFW'] == undefined || param[0]['FUNCTIONID_ZLFW'] == '') {
                                for (var i = 0; i < param.length; i++) {
                                    param[i]['FUNCTIONID_ZLFW'] = $iframe.attr('menuid');
                                }
                            }
                        } else {
                            if (param['FUNCTIONID_ZLFW'] == undefined || param['FUNCTIONID_ZLFW'] == '') {
                                param['FUNCTIONID_ZLFW'] = $iframe.attr('menuid');
                            }
                        }
                    } catch (error) {

                    }
                }
                if (showLoading == undefined) {
                    showLoading = true;
                };
                if (showLoading) {
                    var index = layer.load();
                    if (!url) {
                        layer.close(index);
                        return;
                    }
                }
                method = method || 'get';
                if (method != "get" && method != "GET") {
                    param = (typeof param == 'string') ? param : JSON.stringify(param);
                }
                $.ajax({
                    url: url,
                    type: method,
                    async: async,
                    data: param,
                    dataType: contextType,
                    contentType: "application/json",
                    success: function (result) {
                        callBackFunc(result);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (textStatus == "404") {
                            zlContext.errorMsg("请求地址出错!");
                        } else if (textStatus == "302") {
                            zlContext.errorMsg('连接网页出错!');
                        } else if (textStatus == "timeout") {
                            zlContext.errorMsg("请求超时!");
                        } else {
                            zlContext.errorMsg('请求异常!');
                        }
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        //关闭加载层
                        if (showLoading) {
                            layer.close(index);
                        }
                    }
                });
            },
            /**ajaxPost 提交数据 */
            post: function (url, param, callBackFunc, showLoading) {
                zlContext.zlajax(url, 'post', param, 'json', callBackFunc, true, showLoading);
            },
            /** put 提交数据 */
            put: function (url, param, callBackFunc, showLoading) {
                zlContext.zlajax(url, 'put', param, 'json', callBackFunc, true, showLoading);
            },
            /** put 提交数据 */
            deletePost: function (url, param, callBackFunc, showLoading) {
                zlContext.zlajax(url, 'delete', param, 'json', callBackFunc, true, showLoading);
            },
            /**ajaxGet 提交数据 */
            get: function (url, param, callBackFunc, showLoading) {
                zlContext.zlajax(url, 'get', param, 'json', callBackFunc, true, showLoading);
            },
            /**ajaxGet 提交数据 */
            asyncGet: function (url, param, callBackFunc, showLoading) {
                zlContext.zlajax(url, 'get', param, 'json', callBackFunc, false, showLoading);
            },
            /** 表头提交参数 */
            headerAjax: function (url, method, param, callBackFunc, showLoading) {
                var $iframe = zlContext.getactiveiframe();
                if ($iframe.length > 0 && param != null) {
                    try {
                        if (typeof param == 'string') {
                            param = eval('(' + param + ')');
                        }

                        // 数组
                        if (param instanceof Array) {
                            if (param[0]['FUNCTIONID_ZLFW'] == undefined || param[0]['FUNCTIONID_ZLFW'] == '') {
                                for (var i = 0; i < param.length; i++) {
                                    param[i]['FUNCTIONID_ZLFW'] = $iframe.attr('functionid');
                                }
                            }
                        } else {
                            if (param['FUNCTIONID_ZLFW'] == undefined || param['FUNCTIONID_ZLFW'] == '') {
                                param['FUNCTIONID_ZLFW'] = $iframe.attr('functionid');
                            }
                        }
                    } catch (error) {

                    }
                }
                if (showLoading == undefined) {
                    showLoading = true;
                };
                if (showLoading) {
                    var index = layer.load();
                    if (!url) {
                        layer.close(index);
                        return;
                    }
                }
                method = method || 'get';
                $.ajax({
                    url: url,
                    type: method,
                    async: false,
                    data: param,
                    dataType: 'json',
                    success: function (result) {
                        callBackFunc(result);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (textStatus == "404") {
                            zlContext.errorMsg("请求地址出错!");
                        } else if (textStatus == "302") {
                            zlContext.errorMsg('连接网页出错!');
                        } else if (textStatus == "timeout") {
                            zlContext.errorMsg("请求超时!");
                        } else {
                            zlContext.errorMsg('请求异常!');
                        }
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                        //关闭加载层
                        if (showLoading) {
                            layer.close(index);
                        }
                    }
                });
            },
            /** 获取url的参数 */
            getUrlParam: function () {
                var param = window.location.search,
                    pattern = /([^?&=]+)=([^&#]*)/g,
                    dict = {},
                    search = null;
                if (typeof param === "object" && param instanceof Location) {
                    search = param.search;
                } else if (typeof param === "string") {
                    search = param;
                } else {
                    throw new Error("参数类型非法！请传入window.loaction对象或者url字符串。");
                }
                search.replace(pattern, function (rs, $1, $2) {
                    var key = decodeURIComponent($1),
                        value = decodeURIComponent($2);
                    dict[key] = value;
                    return rs;
                });
                return dict;
            },
            //Show弹出窗口 给地址
            showForm: function (_title, _width, _height, _url, _end, isMaximize, _success) {
                zlContext.showFormEx(2, zlContext.kdayunIframe(), _title, _width, _height, _url, _end, isMaximize, _success);
            },
            //Show弹出窗口 给地址
            showFormEx: function (_type, layerDom, _title, _width, _height, _url, _end, isMaximize, _success) {
                if (zlContext.isEmpty(_width)) {
                    _width = "700px";
                }
                if (zlContext.isEmpty(_height)) {
                    _height = "400px";
                }
                if (parseInt(_width.replace(/[^0-9]/ig, "")) > $(layerDom.document).width()) {
                    _width = $(layerDom.document).width() + "px";
                }
                if (parseInt(_height.replace(/[^0-9]/ig, "")) > $(layerDom.document).height()) {
                    _height = $(layerDom.document).height() + "px";
                }
                var index = layerDom.layer.open({
                    type: _type,
                    title: _title,
                    area: [_width, _height],
                    fixed: true, //不固定
                    scrollbar: true,
                    maxmin: true,
                    content: _url,
                    success: _success,
                    end: _end
                });
                if (isMaximize == "1") {
                    layer.full(index);
                }
            },
            //Show弹出窗口,直接给html
            showContentForm: function (_title, _width, _height, _Content, _end, isMaximize, _success) {
                zlContext.showFormEx(1, window.top, _title, _width, _height, _Content, _end, isMaximize, _success);
            },
            /**返回url 组装参数**/
            getUrlByInputs: function (_url, inputs, data) {
                if (!zlContext.isEmpty(inputs)) {
                    var urlStr = "",
                        inputArr = inputs.split(',');
                    $.each(inputArr, function (i, value) {
                        var paramArr = value.split(':', 2);
                        if (!zlContext.isEmpty(paramArr[0])) {
                            if (!zlContext.isEmpty(urlStr)) {
                                urlStr += '&';
                            }
                            //获取参数值，如果值为空，获取datagrid选中行数据
                            var _vaule = paramArr[1];
                            if (zlContext.isEmpty(_vaule)) //如果值为空或者值是#/$开头   $取参数，#取选择器
                            {
                                _vaule = data[paramArr[0]];
                            } else if ($.startsWith(_vaule, "$")) {
                                _vaule = data[_vaule.substring(1)];
                            } else if ($.startsWith(_vaule, "#")) {
                                _vaule = $(_vaule).val();
                            }
                            if (!zlContext.isEmpty(_vaule)) {
                                urlStr += paramArr[0] + "=" + _vaule;
                            }
                        }
                    });
                    if (_url.indexOf('?') == -1) {
                        _url += "?";
                    }
                    _url += urlStr;
                }
                return _url;
            },
            getCurrentUser: function () {
                var data,
                    url = getTokenIdUrl(layui.cache['contentPath'] + '/admin/coreuser/querycuruserinfo');

                if(userVo){
                    return userVo;
                }
                zlContext.zlajax(url, 'post', '', 'json',
                    function (result) {
                        data = result.obj;
                        userVo = data;
                    }, false);
                return data;
            },
            /**登出*/
            logOut: function (title, text, url, type, dataType, data, callback) {
                parent.layer.confirm(text, {
                    title: title,
                    resize: false,
                    btn: ['确定退出系统', '不，我点错了！'],
                    btnAlign: 'c',
                    icon: 3
                }, function () {
                    location.href = url;
                }, function () {

                })
            },
            /**判断layui form 表单数据是否已修改
             * formId: form表单  form标签的ID值
             * oldFields： 编辑时 表单初始默认渲染值
             * obj： 当前弹窗方法的 父对象
             * index：当前弹窗 index 值
             */
            isFormDataChange: function (formId, oldFields, obj, index) {
                obj.newFields = null;
                // form.on('submit(frmGridDept)', function (frm) {
                //     return newFields = frm.field;
                // });
                if ($('#' + formId).find('.getField').length == 0) {
                    $('#' + formId).append('<button class="layui-btn layui-hide getField" lay-submit lay-filter="' + formId + '">获取表单值</button>');
                }
                var verifyItem = $('#' + formId).find('[lay-verify]');
                for (var i = 0; i < verifyItem.length; i++) {
                    var verifyStr = $(verifyItem[i]).attr('lay-verify');
                    if (verifyStr != '') {
                        $(verifyItem[i]).attr({
                            'lay-verify': '',
                            'data-verifyflag': verifyStr
                        })
                    }
                }
                $('#' + formId).find('.getField').trigger('click');
                if (obj.newFields == null) {
                    return false;
                }
                // var oldFields = gridAction.currentEditObj.data
                if (!zlContext.isObjectValueEqual(obj.newFields, oldFields)) {
                    var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
                        title: '是否关闭',
                        resize: false,
                        btn: ['保存关闭', '确定关闭', '取消'], //按钮
                        btnAlign: 'c',
                        anim: 1,
                        icon: 3
                    }, function () {
                        layer.close(changeConfirmLayer);
                        var items = $('#' + formId).find('[data-verifyflag]');
                        for (var i = 0; i < items.length; i++) {
                            var verifyStr = $(items[i]).attr('data-verifyflag');
                            $(items[i]).attr({
                                'lay-verify': verifyStr,
                                'data-verifyflag': ''
                            });
                        }
                        $('#' + formId).find('.getField').remove()
                        $('#' + formId).find('[lay-submit]').trigger('click')
                        // obj.sumbit(obj.newFields);
                    }, function () {
                        layer.close(index);
                    }, function () {
                        layer.close(changeConfirmLayer);
                    });
                    return false;
                } else {
                    layer.close(index);
                }
            },
            /**判断两个对象相同属性的属性值是否相等
             * 只针对简单一层的 对象
             * 例如：{a:'a',b:'b'}
             * 
             */
            isObjectValueEqual: function (objA, objB) {
                for (var keyA in objA) {
                    for (var keyB in objB) {
                        if (keyA == keyB) {
                            if (objA[keyA] == undefined || objA[keyA] == null) {
                                objA[keyA] = '';
                            }
                            if (objB[keyB] == undefined || objB[keyB] == null) {
                                objB[keyB] = '';
                            }
                            if (objA[keyA] != objB[keyB]) {
                                return false;
                            }
                            break;
                        }
                    }
                }
                return true;
            },
            /** 判断对象是为空 */
            isEmpty: function (value) {
                return (value === null || value == undefined || value === '');
            },
            /**生成一个本地唯一的id */
            generateId: function () {
                return (Math.random() * 10000000).toString(16).substr(0, 4) + (new Date()).getTime().toString(16).substr(5, 6);
            },
            /**格式化字符类似java的format函数 {0} 序号从0开始*/
            format: function (s) {
                var i = arguments.length,
                    ret = s;
                while (i--) {
                    ret = ret.replace(new RegExp('\\{' + (i - 1) + '\\}', 'gm'), arguments[i]);
                }
                return ret;
            },
            /**
             * 格式化数字，千分号分隔
             * num：需格式化的数字 、
             */
            formatNumberByPermil: function (num) {
                var decimalPart = '';
                num = num.toString();
                if (num.indexOf('.') != -1) {
                    decimalPart = '.' + num.split('.')[1];
                    num = parseInt(num.split('.')[0]);
                }
                var array = num.toString().split('');
                var index = -3;
                while (array.length + index > 0) {
                    array.splice(index, 0, ',');
                    index -= 4;
                }
                return array.join('') + decimalPart;
            },
            /**根据数据填充form */
            autoFill: function (frmElem, data, options) {
                var settings = {
                    findbyname: true,
                    restrict: true
                };
                var filler = {
                    checkbox: function ($elem, value) {
                        var valueformat = $elem.attr('valueformat');
                        if ((valueformat != undefined && value === valueformat.split('|')[0]) || value == 1 || value == "true" || value === true)
                            $elem.attr("checked", "checked");
                        else
                            $elem.remove("checked");
                    },
                    radio: function ($elem, value) {
                        value == $elem.val() ? $elem.attr("checked", "checked") : $elem.remove("checked");
                    },
                    zlcomponent: function ($elem, value) {
                        var WParam = {
                            elem: $elem[0],
                            value: value,
                            redraw: true
                        };
                        layui.event('WM_USERDEF', 'WM_DRAW', WParam);
                    },
                    other: function ($elem, value) {
                        $elem.each(function () {
                            $(this).val(value);
                        });
                    }
                }
                if ($(frmElem).length > 0 && $(frmElem)[0].reset) {
                    var self = $(frmElem);
                    $(frmElem)[0].reset();
                    //  清空数据
                    $(':input', frmElem)
                        .not(':button, :submit, :reset, :hidden')
                        .val('')
                        .removeAttr('checked')
                        .removeAttr('selected');
                } else {
                    return;
                }
                if (options) {
                    $.extend(settings, options);
                }
                if (data) {
                    $.each(data, function (field, value) {
                        var selector, elt;
                        if (settings.findbyname) { // by name
                            selector = '[name="' + field + '"]';
                            elt = (settings.restrict) ? self.find(selector) : $(selector);
                            $.each(elt, function (index, item) {
                                var f = field,
                                    v = value,
                                    item = $(item);
                                if (item.attr('zlcomponent') != undefined) {
                                    filler.zlcomponent(item, v);
                                } else if (filler[item.attr('type')]) {
                                    filler[item.attr('type')](item, v);
                                } else {
                                    filler.other(item, v);
                                }
                            });
                        } else { // by id
                            selector = '#' + field;
                            elt = (settings.restrict) ? self.find(selector) : $(selector);

                            if (elt.length == 1) {
                                elt.val((elt.attr("type") == "checkbox") ? [value] : value);
                            } else {
                                var radiofound = false;
                                // radio
                                elt = (settings.restrict) ? self.find('input:radio[name="' + field + '"]') : $('input:radio[name="' + field + '"]');
                                elt.each(function () {
                                    radiofound = true;
                                    if (this.value == value) {
                                        this.checked = true;
                                    }
                                });
                                // multi checkbox
                                if (!radiofound) {
                                    elt = (settings.restrict) ? self.find('input:checkbox[name="' + field + '[]"]') : $('input:checkbox[name="' + field + '[]"]');
                                    elt.each(function () {
                                        $(this).val(value);
                                    });
                                }
                            }
                        }
                    });
                    form.render(); //更新全部
                }
            },
            //获取浏览类型
            browserType: function () {
                var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 
                var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器 
                var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器 
                var isEdge = userAgent.indexOf("Windows NT") > -1 && userAgent.indexOf("Trident") > -1 && !isIE; //判断是否IE的Edge浏览器 
                var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器 
                var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器 
                var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器 

                if (isIE || isEdge) {
                    return "IE";
                }
                if (isFF) {
                    return "FF";
                }
                if (isOpera) {
                    return "Opera";
                }
                if (isSafari) {
                    return "Safari";
                }
                if (isChrome) {
                    return "Chrome";
                }
                if (isEdge) {
                    return "Edge";
                };
            },
            //添加消息对象
            addMessageObj: function (Projtect, ProjectName) {
                messenger.addTarget(Projtect.contentWindow, ProjectName);
            },
            // 发送消息，参数json格式
            postMessage: function (Param, ProjectName) {
                if (ProjectName == '' || ProjectName == undefined) {
                    messenger.send(Param);
                } else {
                    messenger.targets[ProjectName].send(Param);
                }
            },
            listenMasssage: function (callback) {
                messenger.listen(function (msg) {
                    callback(msg);
                });
            },
            // 控制高度布局
            setMaxHeihgt: function (deff) {
                $(".layui-card:last-child").css('margin-bottom', '0');
                var windowH = $(window).height(),
                    $zlToolbar = $(".docking-fill").find(".zl-toolbar"),
                    $layuicardbody = $(".layui-card-body"),
                    $dockingfill = $(".docking-fill"),
                    $dockingleft = $(".docking-left"),
                    $zltreeheader = $(".zltree-header"),
                    $zltreeSearch = $('.layui-search.zltreeMenuSearch'),
                    $zltreebody = $('.zltree-body'),
                    $zlcontainer = $(".zl-container"),
                    $layuitablepage = $zlcontainer.find('.layui-table-page'),
                    zlToolbarH = $zlToolbar.height() + parseFloat($zlToolbar.css("margin-bottom")),
                    layuicardbodyp = parseFloat($layuicardbody.css("padding-top")) + parseFloat($layuicardbody.css("padding-bottom"));
                $dockingfill.height(windowH - 16);
                if ($dockingleft.length > 0) {
                    $dockingleft.height(windowH - 16);
                    var zltreebodyH = parseFloat($zltreebody.css("padding-top")) + parseFloat($zltreebody.css("padding-bottom")),
                        treeHeaderH = $zltreeheader.length > 0 ? $zltreeheader.height() + 1 : 0,
                        treeSearchH = $zltreeSearch.length > 0 ? $zltreeSearch.height() + 10 : 0;
                    $zltreebody.height($dockingleft.height() - treeHeaderH - treeSearchH - zltreebodyH);
                }
                // $zlcontainer.height($dockingfill.height() - layuicardbodyp);
                // zlToolbarH = !zlToolbarH ? 50 : zlToolbarH;
                $zlcontainer.height($dockingfill.height() - (!zlToolbarH ? 0 : zlToolbarH) - layuicardbodyp);
                var layuitablepageH = $layuitablepage.length > 0 ? 41 : 0;
                $zlcontainer.find('.layui-table-view').height($zlcontainer.height());
                $zlcontainer.find('.layui-table-main').height($zlcontainer.height() - layuitablepageH - 39);
                var tableheight = $zlcontainer.height() - deff;
                return tableheight;
            },
            //获取cookie
            getCookies: function(){
                var cookies = {};
                var c = document.cookie + ";";
                var re = /\s?(.*?)=(.*?);/g;
                var matches;
                while ((matches = re.exec(c)) != null) {
                    var name = matches[1];
                    var value = matches[2];
                    if (name) {
                        cookies[name] = value;
                    }
                }
                return cookies;
            },
            //获取cookie值
            getCookieValue: function(cookieName){
                var cookies = zlContext.getCookies();
                if(cookies){
                    return cookies[cookieName];
                }
            },
            /**下载文件 */
            download: function (url, completeCallback) {
                if ($("#ifdownload").length == 0) {
                    $("body").append('<iframe id=ifdownload style="display:none"></iframe>');
                }
                $("#ifdownload").attr("src", url);
                var iframe = $("#ifdownload")[0];
                iframe.onload = iframe.onreadystatechange = function iframeload() {
                    if (!iframe.readyState || iframe.readyState == "complete") {
                        if (completeCallback) {
                            completeCallback();
                        }
                    }
                };
            },
            /**下载文件 post */
            downloadpost: function (params, url) {
                if (!url) {
                    return;
                }
                var html = ('<form id="downloadform" action="' + url + '" method="post" style="display:none">');
                if ($("#downloadform").length > 0) {
                    $("#downloadform").remove();
                }
                if (params) {
                    params = JSON.stringify(params);
                    html += '<input name="model" value=\'' + params + '\'/>';
                }
                // html += ('<iframe id=ifdownloadpost style="display:none"></iframe>');
                html += '</form>';
                $("body").append(html);
                $("#downloadform").prop('action', url);
                $("#downloadform").submit();
            },
            /**
             * countTime ：倒计的时间，单位秒
             * elemId ：显示倒计时的元素id
             * bDisable ：是否设置elemId元素为disabled
             */
            setCountdown: function (countTime, elemId, bDisable) {
                var elemContext = $('#' + elemId).html();
                var thisTimer, zlCountdown = function (countTime, elemId, bDisable) {
                    var startTime = new Date();
                    var endTime = new Date(startTime.getTime() + (countTime * 1000));
                    //设置元素颜色
                    if (bDisable == undefined) {
                        bDisable = true;
                    };
                    clearTimeout(thisTimer);
                    util.countdown(endTime, startTime, function (date, serverTime, timer) {
                        if($('#' + elemId).length <= 0){
                            clearTimeout(timer);
                            return;
                        }
                        if (bDisable) {
                            $('#' + elemId).attr('disabled', true);
                            $('#' + elemId).addClass('layui-btn-disabled');
                        }
                        var second = date[0] * 24 * 3600 + date[1] * 3600 + date[2] * 60 + date[3];
                        var str = '重新获取(' + second + 's)';
                        $('#' + elemId).html(str);
                        if (0 == date[0] && 0 == date[1] && 0 == date[2] && 0 == date[3]) {
                            $('#' + elemId).removeAttr('disabled')
                                .removeClass('layui-btn-disabled')
                                .html(elemContext);

                        }
                        thisTimer = timer;
                    });
                };
                zlCountdown(countTime, elemId, bDisable);
            },
            /**校验手机号 */
            verifyPhone: function (phone, errorMsg) {
                if (!phone || !/^1\d{10}$/.test(phone)) {
                    if (errorMsg) {
                        layer.msg(errorMsg);
                    }
                    return false;
                }
                return true;
            },
             /** 从顶级遍历iframe层级、获取我们系统的最顶层 */
            kdayunIframe: function () {
                var parentIframe = parent;
                var iframes = self;
                var windowTop = window.top
                // 判断顶层的body是不是我们系统的界面
                var getTopInterface = iframes.document.body;
                if ($(getTopInterface).attr('id') == 'zhengling-zhuye') {
                    parentIframe = iframes
                } else {
                    // 递归获取到iframe如果它子集的bogy带有我们系统的标识则在该iframe弹出
                    var getParentIframe = function (iframe) {
                        getTopInterface = iframe.document.body
                        if ($(getTopInterface).attr('id') == 'zhengling-zhuye') {
                            return parentIframe = iframe
                        } else if (windowTop == iframe) {
                            return parentIframe = iframe
                        } else {
                            parentIframe = iframe.parent;
                            getParentIframe(parentIframe);
                        }
                    }
                    getParentIframe(parentIframe);
                }
                return parentIframe
            },
        }

    /**
     * input框 placeholder 属性兼容
     */
    // 判断浏览器是否支持placeholder属性
    function isSupportPlaceholder() {
        var input = document.createElement('input');
        return 'placeholder' in input;
    }
    setTimeout(function () {
        if (!isSupportPlaceholder()) {
            $('input[placeholder]').each(function (i) {
                // var phVal = $(this).attr("placeholder");
                $(this).css({
                    'line-height': $(this).height() + 'px',
                    'height': $(this).height() + 2 + 'px',
                    'color': '#999'
                });
                // if ($(this).attr('type') == 'password') {
                var pwdField = $(this),
                    pwdVal = pwdField.attr('placeholder'),
                    pwdId = pwdField.attr('id');
                if (pwdId == '' || pwdId == undefined) {
                    pwdId = pwdField.attr('class').split(' ')[0];
                }
                // 重命名该input的id为原id后跟1

                if ($(this).attr('type') == 'password') {
                    var pwdPlaceholder = '<input class="layui-input" id="' + pwdId + i + '" type="text" value=' + pwdVal + ' autocomplete="off" />';
                } else {
                    if ($(this).val() == '') {
                        var pwdPlaceholder = pwdField.clone();
                        pwdPlaceholder.attr({
                            'id': pwdId + i,
                            // 'type': 'text',
                            'value': pwdVal,
                            'name': pwdField.attr('name') + i,
                            'autocomplete': 'off'
                        });
                        pwdField.after(pwdPlaceholder);
                        var pwdPlaceholder = $('#' + pwdId + i);

                        pwdPlaceholder.show();
                        pwdField.hide();
                        pwdPlaceholder.focus(function () {
                            pwdPlaceholder.hide();
                            pwdField.show();
                            pwdField.focus();
                        });
                        pwdField.blur(function () {
                            if (pwdField.val() == '') {
                                pwdPlaceholder.show();
                                pwdField.hide();
                            }
                        });
                    }
                }
            })
        }
    }, 500)

    //扩展字符串
    String.prototype.endWith = function (endStr) {
        if (endStr != undefined) {
            var d = this.length - endStr.length;
            return (d >= 0 && this.lastIndexOf(endStr) == d);
        } else {
            return false;
        }
    }
    //扩展array的indexOf方法
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (elt /*, from*/ ) {
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ?
                Math.ceil(from) :
                Math.floor(from);
            if (from < 0)
                from += len;
            for (; from < len; from++) {
                if (from in this &&
                    this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
    //扩展array的forEach方法
    if (typeof Array.prototype.forEach != 'function') {
        Array.prototype.forEach = function (callback) {
            for (var i = 0; i < this.length; i++) {
                callback.apply(this, [this[i], i, this]);
            }
        };
    }
    //得到元素的索引
    Array.prototype.removeElem = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
    // 解决ie下对象不支持“bind”属性或方法
    if (!Function.prototype.bind) {
        Function.prototype.bind = function (oThis) {
            if (typeof this !== "function") {
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }
            var aArgs = Array.prototype.slice.call(arguments, 1),
                fToBind = this,
                fNOP = function () {},
                fBound = function () {
                    return fToBind.apply(this instanceof fNOP && oThis ?
                        this :
                        oThis,
                        aArgs.concat(Array.prototype.slice.call(arguments)));
                };
            fNOP.prototype = this.prototype;
            fBound.prototype = new fNOP();
            return fBound;
        };
    }
    // /** 页面加载完成后去除遮罩 */
    // setTimeout(function () {
    //     $('.layadmin-tabsbody-shade', parent.document).hide();
    // }, 600)

    exports('zlContext', zlContext);
});